﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections.Specialized;
using Av.Utils;

namespace JrGreenMonster
{
    class IttcWebClient : WebClient
    {

        protected int m_timeoutMs = 60000;

        /// <summary>
        /// Gets/sets timeout in ms
        /// </summary>
        public int TimeoutMs { get { return m_timeoutMs; } set { m_timeoutMs = value; } }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest rq = base.GetWebRequest(address);
            rq.Timeout = m_timeoutMs;
            return rq;
        }

        /// <summary>
        /// Uploads 
        /// </summary>
        /// <param name="urlToSend"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public string PostCstSignals(string urlToSend, string filename)
        {
            string resp = "";
            byte[] ba = null;
            string csrfToken = "";
            NameValueCollection f = new NameValueCollection();
            

            // Got parsed CST signals and prepare form values
            CstSignalItem[] ar = IttcDataFormatter.Parse(filename);
            for(int i = 0; (ar != null) && (i < ar.Length); i++)
            {
                //Log4cs.Log("{0}:{1}:{2}", ar[i].CstName, ar[i].AssetName, ar[i].Price);
                f.Add("l_" + i, ar[i].ToCsv());
            }

            // Get for w/ CSRF token
            resp = DownloadString(urlToSend);
            if((csrfToken = Common.GetCsrfToken(resp)) != string.Empty)
            {
                TimeoutMs = 5 * 60 * 1000;
                Log4cs.Log("Upload timeout is set to {0} ms...", TimeoutMs);

                Log4cs.Log(Importance.Debug, "Got CSRF token from ITTC upload form: {0}", csrfToken);
                // Need to add CSRF token to cookies and to form to pass to Django security
                f.Add("csrfmiddlewaretoken", csrfToken);
                Headers.Add(HttpRequestHeader.Cookie, "csrftoken=" + csrfToken);

                ba = UploadValues(urlToSend, "POST", f);
                resp = Encoding.UTF8.GetString(ba);

                Log4cs.Log("Response from ITTC server:{0}{1}", Environment.NewLine, resp);
            } else
            {
                resp = string.Empty;
            }

            return resp;
        }
    }
}
